package com.pinyoumei.app.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.bean.ChangePhoneBean;
import com.pinyoumei.app.bean.CodeBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.NetWorkUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2020-08-18.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2020-08-18        Administrator             新增Person类
 * 2020-08-18        Administrator             增加sex属性
 * 更换手机号
 */
public class ChangePhoneActivity extends BaseActivity implements View.OnClickListener {

    private TimeCount timeCount;//计时器类
    private TextView tvPhone;
    private EditText etCode;
    private TextView tvSendCode;
    private Button btNext;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_phone);

        InitWidget();


        InitData();
    }

    private void InitWidget() {

        RelativeLayout relativeFinish = findViewById(R.id.relative_finish);
        relativeFinish.setOnClickListener(this);
        tvPhone = findViewById(R.id.tv_phone);
        etCode = findViewById(R.id.et_code);
        tvSendCode = findViewById(R.id.tv_send_code);
        tvSendCode.setOnClickListener(this);
        btNext = findViewById(R.id.bt_next);
        btNext.setOnClickListener(this);

        timeCount = new TimeCount(60 * 1000, 1000);

        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>0){
                    btNext.setBackground(ContextCompat.getDrawable(ChangePhoneActivity.this,R.drawable.shanpe_green_5dp));

                }else{
                    btNext.setBackground(ContextCompat.getDrawable(ChangePhoneActivity.this,R.drawable.shanpe_gray_green_5dp));

                }
            }
        });
    }


    private void InitData() {
        Map<String,Object> map = new HashMap<>();
        map.put("user_id",SPUtils.getAppUserId(this));

        OkGo.<String>post( Constants.UPDATE_PHONE_FIRST)
                .params("user_id",SPUtils.getAppUserId(this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {




                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        ChangePhoneBean changePhoneBean = gson.fromJson(response.body(), ChangePhoneBean.class);
                        if (changePhoneBean.getCode() >= 0 ){
                            tvPhone.setText(changePhoneBean.getResult().getUser_phone()+"");
                        }else{
                            ToastUtils.showShort(changePhoneBean.getMsg());
                            finish();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.relative_finish:
        		finish();
        		break;
        		case R.id.tv_send_code:
                    if (!NetWorkUtils.isNetworkConnected(this)) {
                        Toast.makeText(this, "当前网络不可用，请检查网络状态！", Toast.LENGTH_SHORT).show();
                        return;
                    }


                    if (!TextUtils.isEmpty(tvPhone.getText().toString().trim())){
                        SendCode(tvPhone.getText().toString(), 5);


                    }else {
                        Toast.makeText(mContext, "手机号查找不存在", Toast.LENGTH_SHORT).show();
                    }


                    break;

            case R.id.bt_next:
                String code = etCode.getText().toString().trim();
                phone_submit(code);
                break;

        	default:
        		break;
        }
    }


    //计时器类
    class TimeCount extends CountDownTimer {
        //构造方法
        public TimeCount(long millisInFuture, long countDownInterval) {//第一个参数是计时器的总时间是60s 第二个参数是间隔是1s
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvSendCode.setText("重新获取(" + millisUntilFinished / 1000 + "s)");
            tvSendCode.setTextColor(Color.parseColor("#438FF5"));
            tvSendCode.setClickable(false);
        }

        @Override
        public void onFinish() {
            tvSendCode.setText("获取验证码");
            tvSendCode.setTextColor(Color.parseColor("#438FF5"));
            tvSendCode.setClickable(true);
        }
    }


    private void SendCode(String phone,int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", phone);
        map.put("type", type);

        OkGo.<String>post(Constants.SendMSG)
                .params("user_phone", phone)
                .params("type", type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        CodeBean codeBean = gson.fromJson(response.body(), CodeBean.class);

                        if (codeBean.getCode() >= 0) {

                            if (timeCount == null) {
                                timeCount = new TimeCount(60 * 1000, 1000);//5s的一个定时器 间隔是1s
                                timeCount.start();

                            }

                            Toast.makeText(ChangePhoneActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(ChangePhoneActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }









    private void phone_submit(String verify_code) {
        Map<String,Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(this));
        map.put("verify_code", verify_code);

        OkGo.<String>post( Constants.UPDATE_PHONE_SUBMIT)
                .params("user_id",SPUtils.getAppUserId(this))
                .params("verify_code", verify_code)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {




                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.getCode() >= 0 ){
                            startActivity(new Intent(ChangePhoneActivity.this,BindPhoneActivity.class));

                        }else{
                            ToastUtils.showShort(baseBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}
